import { useState, useEffect, useCallback } from 'react';
import { TextareaStyled } from './style';
import { TokenProps } from '@/interface';
import { MonkeyLexer } from '@/utils';

interface NodeFiber {
  node?: any;
  begin?: number;
  end?: number;
  token?: TokenProps;
}

const MonkeyEditor = ({
  keywords,
}: {
  keywords: { [key in string]: TokenProps };
}) => {
  const [keyWordElementArray, setKeyWordElementArray] = useState<NodeFiber[]>(
    [],
  );
  let lastBegin = 0;

  const notifyTokenCreation = useCallback(
    (token, elementNode, begin, end) => {
      if (keywords[token.getLiteral()] !== undefined) {
        const e: NodeFiber = {};

        e.node = elementNode;
        e.begin = begin;
        e.end = end;
        e.token = token;
        elementNode.keyWordCount++;

        keyWordElementArray.push(e);
        setKeyWordElementArray((data) => {
          return [...data];
        });
      }
    },
    [keywords],
  );

  const changeNode = useCallback((n) => {
    let f = n.childNodes;

    for (let c of f) {
      changeNode(f[c]);
    }

    if (n.data) {
      lastBegin = 0;
      n.keyWordCount = 0;

      let lexer = new MonkeyLexer(n.data);
      lexer.setLexingObserver(this, n);
      lexer.lexing();
    }
  }, []);

  return <TextareaStyled className="ide-textarea" contentEditable />;
};

export default MonkeyEditor;
